function [TransMat,EP] = EstTransMat (Pt, It,P,I)
% Estimates the transition matrix given a vector of prices
% Inputs:
%   Pt = Tx1 vector of observed price bins
%   It = Tx1 vector of intervals
% Assume that Pt and It are sorted by date and interval


T = size(Pt,1);
% look at the next P
Pnext = Pt([ 2:end  1]);

% get the highest and lowest price bin
%P_min = min(Pt);
%P_max = max(Pt);

% generate dummies
Dummies = dummyvar(It);
size(Dummies);
Dummies = Dummies(:,2:end);  % drop one dummy, interval 1

% generate the square of the bins
Pt2 = Pt.*Pt;

%updated the vectors to match Pnext 12/28/2011; don't know why this was working before
% create the matrix
X = [ones(T,1),Pt,Pt2,Dummies];
X = X(1:(T-1),:);  % lop off last obs
Pnext = Pnext(1:(T-1),1);

% estimate beta
beta = inv(X'*X)*X'*Pnext;
uhat = Pnext-X*beta;
sigma = sqrt(sum(uhat.*uhat)/(size(X,1)));
EP = X*beta;

% CONDITIONAL PROBABILITIES
    % for all but the dropped interval
    phat = zeros(P,I);

    % calculate expected bin (continous) for each possible price and interval
        Ptvector = (1:P)';
        Pt2vector = Ptvector.*Ptvector;
        for i = 2:I   % for all but the dummy that was dropped
                phat(:,i) = beta(1,1) + beta(2,1)*Ptvector + beta(3,1)*Pt2vector + beta(i+2,1); 
        end
        phat(:,1) = beta(1,1) + beta(2,1)*Ptvector + beta(3,1)*Pt2vector;   % for the dummy that was dropped
    
   

% calculate the transitition matrix
TransMat = zeros(P,P,I);
% calculate the probability for each
for i = 1:I
    for p = 1:P
        %(1:P) is a row vector of price bins
        TransMat(p,:,i) = normpdf((1:P),phat(p,i),sigma)./sum(normpdf((1:P),phat(p,i),sigma));
    end
end

% % TESTING
% for i = 1:I
%     for p = 1:P
%         %(1:P is a row vector of price bins
%         yes(i,p) = sum(TransMat(:,p,i));
%     end
% end
% min(min(yes))



% from matlab help, residuals have different variances which depend on
% the value of their predictors (How?) (heteroskedasticity??)

